using GamFi.API.Application.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace GamFi.API.Persistence.Context;

/// <summary>
/// Скрипт для накатывания миграций
/// </summary>
public class Migrator
{
    private readonly EfContext _efContext;
    private readonly IDbSeeder _dbSeeder;
    private readonly ILogger<Migrator> _logger;

    /// <summary>
    /// Конструктор
    /// </summary>
    /// <param name="efContext">Контекст БД</param>
    /// <param name="dbSeeder">Сид сервис</param>
    /// <param name="logger">Логгер</param>
    public Migrator(
        EfContext efContext,
        IDbSeeder dbSeeder,
        ILogger<Migrator> logger)
    {
        _efContext = efContext;
        _dbSeeder = dbSeeder;
        _logger = logger;
    }
    
    public async Task MigrateAsync(CancellationToken cancellationToken)
    {
        try
        {
            var migrationId = Guid.NewGuid();
            _logger.LogInformation($"Started applying migration {migrationId}");
            await _efContext.Database.MigrateAsync(cancellationToken).ConfigureAwait(false);
            await _dbSeeder.SeedAsync(_efContext, cancellationToken);
            _logger.LogInformation($"End applying migration {migrationId}");
        }
        catch (Exception e)
        {
            _logger.LogCritical($"Apply migrations is field {e.Message}");
            throw;
        }
    }
}